import Vue from 'vue'
import VueRouter from 'vue-router'
import modules from "./modules";
import store from '../store'

Vue.use(VueRouter)



const router = new VueRouter({
    mode: 'hash',
    base: process.env.BASE_URL,
    routes: [...modules]
})

router.$addRoutes = (params) => {
    router.matcher = new VueRouter({ mode: 'history' }).matcher
    router.addRoutes(params)
}

router.beforeEach((to, from, next) => {
    //c从缓存中获取活动的tabs列表
    store.dispatch("menustore/getTabsAction");
    // 从缓存中获取激活的tab
    store.dispatch("menustore/setActiveTabsAction", to.name);

    let accessToken = sessionStorage.getItem("accessToken");
    if (to.path === '/login') {
        if (accessToken) {
            next({path:'/home'})
        } else {
            next();
        }
    } else {
        if (!accessToken && to.name != 'login') {
            next({path: "/login"})
        } else {
            if (store.state.loginstore.menu_data.length === 0) {
                store.dispatch("loginstore/getMenuListAction", router).then(()=>{
                    if (to.path == "/") {
                        next({path: '/home'})
                    } else {
                        next({path:to.path});
                    }
                })
            } else {
                next();
            }
        }
    }
    // 解决刷新后菜单数据不存在的问题


})
export default router
